package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.constant.WeChatConstent;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //调用微信接口获取openid
        String openid = getOpenid(userLoginDTO.getCode());
        //判断openid是否为空
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断用户是否为新用户，新用户则要完成注册
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }

    /**
     * 调用微信获取openid
     *
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        HashMap<String, String> parms = new HashMap<>();
        parms.put(WeChatConstent.WX_LOGIN_APPID, weChatProperties.getAppid());
        parms.put(WeChatConstent.WX_LOGIN_SECRET, weChatProperties.getSecret());
        parms.put(WeChatConstent.WX_LOGIN_JSCODE, code);
        parms.put(WeChatConstent.WX_LOGIN_GRANT_TYPE, WeChatConstent.WX_LOGIN_GRANT_TYPE_VALUE);
        //把请求参数传递给微信 获取openid

        String openid = JSONObject.parseObject(HttpClientUtil.doGet(WeChatConstent.WX_LOGIN_URL, parms))
                .getString(WeChatConstent.WX_LOGIN_OPENID);
        return openid;
    }
}
